package com.moss.cloud.base.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moss.cloud.base.api.model.from.BaseFrom;
import com.moss.cloud.base.api.model.from.FlowTaskFrom;
import com.moss.cloud.base.api.model.param.FlowTaskParam;
import com.moss.cloud.base.api.model.vo.FlowTaskVO;
import com.moss.cloud.base.biz.mapper.FlowTaskMapper;
import com.moss.cloud.base.biz.model.FlowTask;
import com.moss.cloud.base.biz.service.IFlowTaskService;
import com.moss.cloud.base.biz.service.ISysUserService;
import com.moss.cloud.common.base.model.po.SysUser;
import com.moss.cloud.common.base.utils.PageUtil;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.utils.BooleanHandel;
import com.moss.cloud.common.core.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 流程任务业务实现
 *
 * @author 瑾年
 * @date 2024-04-13
 */
@Slf4j
@Service
@EnableAspectJAutoProxy(exposeProxy = true)
public class FlowTaskServiceImpl extends ServiceImpl<FlowTaskMapper, FlowTask> implements IFlowTaskService {

    private final ISysUserService sysUserService;
    public FlowTaskServiceImpl(ISysUserService sysUserService){
        this.sysUserService = sysUserService;
    }
    /**
     * 分页查询-当前登录人的代办任务
     *
     * @param param
     * @return
     */
    @Override
    public IPage<FlowTask> page(FlowTaskParam param) {
        Page<FlowTask> page = PageUtil.createPage(param.getCurrent(), param.getSize());
        return this.page(page, new QueryWrapper<FlowTask>().lambda()
                .like(StringUtils.isNotBlank(param.getName()), FlowTask::getName, param.getName())
                .like(StringUtils.isNotBlank(param.getTitle()), FlowTask::getTitle, param.getTitle())
                .eq(Objects.nonNull(param.getStatus()), FlowTask::getStatus, param.getStatus())
                .like(FlowTask::getHeadUsers, UserContextHolder.getUserId()));
    }

    /**
     * 审批人抄送人信息
     *
     * @param userIds
     * @return
     */
    @Override
    public List<FlowTaskVO.ApprovalUser> approvalUsers(List<Long> userIds) {
        List<SysUser> sysUsers = sysUserService.list(new QueryWrapper<SysUser>().lambda().in(SysUser::getId, userIds));
        return CollectionUtils.isNotEmpty(sysUsers) ? sysUsers.stream().map(x -> {
            FlowTaskVO.ApprovalUser approvalUser = new FlowTaskVO.ApprovalUser();
            BeanUtils.copyProperties(x, approvalUser);
            return approvalUser;
        }).collect(Collectors.toList()) : Collections.emptyList();
    }

    /**
     * 新增
     *
     * @param from
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveFlowTask(FlowTaskFrom from) {
        FlowTask flowTask = new FlowTask();
        BeanUtils.copyProperties(from, flowTask);
        return this.save(flowTask);
    }

    /**
     * 更新
     *
     * @param from
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(FlowTaskFrom from) {
        BooleanHandel.trueThrow(Objects.isNull(from.getId())).throwMessage(SystemErrorType.PRIMARY_KEY);
        FlowTask flowTask = this.getById(from.getId());
        BooleanHandel.trueThrow(Objects.isNull(flowTask)).throwMessage(SystemErrorType.DATE_EMPTY);
        FlowTask model = new FlowTask();
        BeanUtils.copyProperties(from, model);
        model.setApplyTime(LocalDateTime.now());
        return this.updateById(model);
    }


    /**
     * 删除
     *
     * @param baseFrom
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(BaseFrom baseFrom) {
        FlowTask flowTask = this.getById(baseFrom.getId());
        BooleanHandel.trueThrow(Objects.isNull(flowTask)).throwMessage(SystemErrorType.DATE_EMPTY);
        return this.removeById(baseFrom.getId());
    }

    /**
     * 详情
     *
     * @param baseFrom
     * @return
     */
    @Override
    public FlowTaskVO detail(BaseFrom baseFrom) {
        FlowTask flowTask = this.getById(baseFrom.getId());
        BooleanHandel.trueThrow(Objects.isNull(flowTask)).throwMessage(SystemErrorType.DATE_EMPTY);
        FlowTaskVO flowTaskVO = new FlowTaskVO();
        BeanUtils.copyProperties(flowTask, flowTaskVO);
        flowTaskVO.setApprovalUsers(this.approvalUsers(Arrays.stream(flowTask.getHeadUsers().split(",")).map(Long::valueOf)
                .collect(Collectors.toList())));
        flowTaskVO.setCcUsers(this.approvalUsers(Arrays.stream(flowTask.getCcToUsers().split(",")).map(Long::valueOf)
                .collect(Collectors.toList())));
        return flowTaskVO;
    }

    /**
     * 批量保存任务
     *
     * @param flowTasks
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatchFlowTask(List<FlowTask> flowTasks) {
        return ((FlowTaskServiceImpl) AopContext.currentProxy()).saveBatch(flowTasks);
    }

    /**
     * 批量删除任务
     *
     * @param busId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeBatchFlowTask(Long busId) {
        return this.remove(new QueryWrapper<FlowTask>().lambda().eq(FlowTask::getBusId, busId));
    }

}
